<template>
	<view class="goods-order" :class="themeName">

		<view class="leader-info p-30 flex">
			<view style="width: 50rpx;" class="flex col-top">
				<u-icon name="map" size="30" color="rgba(105, 193, 103, 1)" />
			</view>
			<view class="info">
				<view class="address">{{leaderInfo.region_address}}</view>
				<view class="name flex">
					<view class="badge m-r-10" :style="{
							backgroundImage: `url(${$getImageUri('resource/image/shopapi/uniapp/leader-badge.png')})`
						}">{{$zhTran('团长')}}</view>
					<text>{{leaderInfo.name}} {{leaderInfo.phone}}</text>
				</view>
			</view>
		</view>
		<view class="leader-address p-30 m-t-20">
			<view class="flex col--center u-border-bottom p-t-20 p-b-20">
				<u-icon name="clock" size="30" color="rgba(105, 193, 103, 1)" />
				<view class="title">{{$zhTran('开始提货时间')}}：<text>{{orderInfo.pickup_time}}</text></view>
			</view>
			<view class="flex col--center u-border-bottom p-t-20 p-b-20">
				<u-icon name="account" size="30" color="rgba(105, 193, 103, 1)" />
				<view class="title">{{$zhTran('提货人')}}：<text>{{orderInfo.user_name}}</text></view>
			</view>
			<view class="flex col--center u-border-bottom p-t-20 p-b-20">
				<u-icon name="phone" size="30" color="rgba(105, 193, 103, 1)" />
				<view class="title">{{$zhTran('手机号')}}：<text>{{orderInfo.user_phone}}</text></view>
			</view>
		</view>

		<!-- 订单商品 -->
		<view class="contain">
			<!-- 商品列表 -->
			<view class="goods">
				<view v-for="item in orderGoodsList" :key="item.id" class="goods-item">
					<goods-card shape="rectangle" :name="item.goods_name" :image="item.image"
						:contain-style="{ 'border-raius': 0, height: '160rpx' }"
						:image-style="{ width: '160rpx', height: '160rpx' }">
						<view class="flex-1" slot="default">
							<u-gap height="80"></u-gap>
							<view class="m-t-10 flex row-between">
								<view class="flex">
									<!-- 售价 -->
									<price :content="item.sell_price" mainSize="32rpx" minorSize="24rpx"
										color="rgba(250, 64, 52, 1)" :prefix="orderInfo.price_symbol" />
								</view>

								<text class="lighter sm">x{{ item.goods_num }}</text>
							</view>
						</view>
					</goods-card>
				</view>
			</view>

		</view>

		<!-- 优惠 -->
		<view class="contain discounts">
			<!-- 优惠券 -->
			<view class="cell discounts-item" @tap="showCoupons = true">
				<view class="cell-lable">{{$zhTran('优惠券')}}</view>
				<view class="cell-content m-r-10" :style="{color: themeColor}">{{ couponsActive.name || '' }}</view>
				<u-icon name="arrow-right" />
			</view>
		</view>

		<!-- 订单清算 -->
		<view class="contain clearing">
			<view class="cell clearing-item">
				<view class="cell-label">{{$zhTran('商品金额')}}</view>
				<view class="cell-content">
					<price :content="orderInfo.total_goods_price" color="rgba(250, 64, 52, 1)"
						:prefix="orderInfo.price_symbol" />
				</view>
			</view>
			<view class="cell clearing-item">
				<view class="cell-label">{{$zhTran('优惠券')}}</view>
				<view class="cell-content">
					<price :content="orderInfo.discount_amount" :prefix="'-'+orderInfo.price_symbol"
						color="rgba(250, 64, 52, 1)" />
				</view>
			</view>
		</view>

		<!-- 订单操作 -->
		<view class="operational">
			<view class="order-amount">
				<view class="flex">
					<text>{{$zhTran('合计')}}:</text>
					<price :content="orderInfo.order_amount" mainSize="38rpx" minorSize="30rpx"
						color="rgba(250, 64, 52, 1)" :prefix="orderInfo.price_symbol" />
				</view>
				<view class="flex" style="color: rgba(166, 166, 166, 1);font-size: 22rpx;">
					<text>{{$zhTran('已省')}}:</text>
					<price :content="orderInfo.reduced_amount" mainSize="22rpx" minorSize="22rpx"
						color="rgba(166, 166, 166, 1)" :prefix="'-'+orderInfo.price_symbol" />
				</view>
			</view>
			<view class="operational-button" @tap="onSubmitOrder">{{$zhTran('提交订单')}}</view>
		</view>


		<!-- 优惠券【弹窗】 -->
		<u-popup v-model="showCoupons" mode="bottom" border-radius="14" :closeable="false"
			:safe-area-inset-bottom="true" @open="openCouponsPopup" @close="closeCouponsPopup">
			<view class="coupons">
				<view class="coupons-header">
					<text>{{$zhTran('优惠券')}}</text>
					<u-icon name="close" color="#666666" @tap="showCoupons = false" />
				</view>

				<view class="coupons-main">
					<view class="coupons-main__tabs">
						<u-tabs v-if="showCoupons" :list="couponTabsList" :is-scroll="false" :current="couponTabsIndex"
							:height="80" :active-color="themeColor" :bar-style="{top: '100%'}" :bar-width="100"
							:show-bar="true" @change="index => couponTabsIndex = index" />
					</view>

					<view class="coupons-main__contain">
						<!-- 可用优惠券 -->
						<scroll-view :scroll-y="true" style="height: 700rpx;"
							v-show="couponsTabActive['sign'] === 'usable'">
							<view class="coupons-item" v-for="item in couponsInfo.can_use" :key="item.id">
								<coupon-card mode='radio' :name="item.name" :money="item.money"
									:condition="item.condition_tips" :conditionWay="item.condition_way_tips"
									:time="item.use_time_tips" :scene="item.goods_tips" :coupon-id="item.id"
									:checked.sync="item.checked" :prefix="orderInfo.price_symbol"
									:desc="{title: item.fail_use_tips, content: item.fail_use_detail}"
									@change="changeCouponUse(item, $event)" />
							</view>
							<u-empty v-if="!couponsInfo.can_use.length" :text="$zhTran('暂无优惠券')"
								:src="$getImageUri('resource/image/shopapi/uniapp/empty/coupon_icon.png')"
								:icon-size="180" />
						</scroll-view>
						<!-- 不可用优惠券 -->
						<scroll-view :scroll-y="true" style="height: 700rpx;"
							v-show="couponsTabActive['sign'] === 'disabled'">
							<view class="coupons-item" v-for="item in couponsInfo.not_can_use" :key="item.id">
								<coupon-card mode='normal' :name="item.name" :money="item.money"
									:condition="item.condition_tips" :conditionWay="item.condition_way_tips"
									:time="item.use_time_tips" :scene="item.goods_tips" :coupon-id="item.id"
									:prefix="orderInfo.price_symbol"
									:desc="{title: item.fail_use_tips, content: item.fail_use_detail}" />
							</view>
							<u-empty v-if="!couponsInfo.not_can_use.length" :text="$zhTran('暂无优惠券')"
								:src="$getImageUri('resource/image/shopapi/uniapp/empty/coupon_icon.png')"
								:icon-size="180" />
						</scroll-view>
					</view>
				</view>

				<view class="coupons-footer">
					<view class="coupons-footer-button" @tap="useCoupon">{{$zhTran('确认')}}</view>
				</view>
			</view>
		</u-popup>


		<!-- 页面状态 -->
		<page-status :status="pageStatus">
			<template #error>
				<u-empty :text="pageErrorMsg" :src="$getImageUri('resource/image/shopapi/uniapp/empty/order.png')"
					:icon-size="280" />
			</template>
		</page-status>
	</view>
</template>

<script>
	/**
	 * @description 订单结算页
	 * @query { Object } payload 请求数据参数
	 * @example { from: OrderTypeEnum['GOODS'], payload: {source: 'buy_now', goods: {goods_num: 1, item_id: 24} }}
	 */

	import {
		apiCommunityGroupPurchaseLeaderDetail,
		apiCommunityGroupPurchaseOrderPlace,
	} from '@/api/community_group_purchase'
	import {
		PageStatusEnum,
		OrderTypeEnum,
		PaymentStatusEnum,
		PayWayEnum
	} from '@/utils/enum'
	import {
		apiCouponCGPGoods
	} from '@/api/store'

	export default {
		name: 'CGPGoodsOrder',

		data() {
			return {
				// 页面状态
				pageStatus: PageStatusEnum['LOADING'],
				pageErrorMsg: '', // 页面异常信息

				pageQueryPayload: {}, // 承载页面参数
				// 订单表单
				orderFrom: {
					coupon_list_id: '', // 优惠券ID
				},

				orderInfo: {}, // 订单信息
				orderGoodsList: [], // 订单商品
				leaderInfo: [],
				eventChannel2: null,

				/** S 优惠券 **/
				showCoupons: false, // 优惠券: 显示|隐藏【弹窗】
				// 优惠券Tabs列表
				couponTabsList: [{
					sign: 'usable',
					name: this.$zhTran('可使用优惠券'),
				}, {
					sign: 'disabled',
					name: this.$zhTran('不可使用优惠券'),
				}],
				couponTabsIndex: 0, // 优惠券Tabs索引
				// 优惠券信息
				couponsInfo: {
					can_use: [],
					not_can_use: [],
				},
				couponsActive: {}, // 当前使用优惠券
				/** E 优惠券 **/

			}
		},

		computed: {
			// 过滤订单表单冗余参数
			orderFormParams() {
				const from = {
					...this.orderFrom
				}

				return from
			},
			// 当前优惠券Tab
			couponsTabActive() {
				return this.couponTabsList[this.couponTabsIndex]
			},
		},

		methods: {
			// 根据商品类型初始化订单数据
			initOrderData() {
				return new Promise((resolve, reject) => {
					apiCommunityGroupPurchaseOrderPlace({
						...this.orderFormParams,
						...this.pageQueryPayload,
						action: 'settle',
					}).then(ndata => {
						let data = this.$zhTran(ndata)
						this.orderGoodsList = data.goods
						this.orderInfo = data
						resolve(data)
					}).catch(errMsg => reject(errMsg))
				})
			},
			getLeaderInfo() {
				return apiCommunityGroupPurchaseLeaderDetail({
					leader_id: this.pageQueryPayload.leader_id
				}).then((data) => {
					this.leaderInfo = this.$zhTran(data)
					return Promise.resolve(data);
				}).catch(err => {
					return Promise.reject(err);
				});
			},

			// 点击提交订单
			onSubmitOrder() {
				uni.showModal({
					title: this.$zhTran('温馨提示'),
					content: this.$zhTran('是否确认下单?'),
					confirmColor: this.themeColor,
					success: async ({
						confirm
					}) => {
						try {
							if (!confirm) throw this.$zhTran('订单取消')

							// 下单处理
							this.handlePlaceOrder()
						} catch (errMsg) {
							console.log('ORDER_ERROR_MSG:', errMsg)
						}
					}
				});
			},

			// 下单处理
			handlePlaceOrder() {
				return new Promise((resolve, reject) => {
					apiCommunityGroupPurchaseOrderPlace({
						...this.orderFormParams,
						...this.pageQueryPayload,
						action: 'buy',
					}).then(data => {
						// 监听全局duringPayment事件
						uni.$once('duringPayment', data => {
							this.handlePayResult(data)
						})

						return data
					}).then(({
						type,
						order_id
					}) => {
						// 去支付
						this.$Router.replace({
							path: `/bundle2/pages/payment/payment`,
							query: {
								from: type,
								order_id,
							}
						})

						resolve(order_id)
					}).catch(errMsg => reject(errMsg))
				})
			},

			// 支付结果处理
			handlePayResult({
				result,
				order_id
			}) {
				switch (result) {
					case PaymentStatusEnum['SUCCESS']:
					case PaymentStatusEnum['FAIL']:
						this.$Router.replace({
							path: '/bundle2/pages/payment_result/payment_result',
							query: {
								order_id,
								from: 'cgp_order'
							}
						})
						break
					case PaymentStatusEnum['CLOSE']:
						this.$Router.push({
							path: '/bundle2/pages/payment_result/payment_result',
							query: {
								order_id,
								from: 'cgp_order'
							}
						})
						break
				}
			},
			/** S 优惠券 **/
			// 初始化优惠券列表
			initCouponGoods() {
				return new Promise((resolve, reject) => {
					let params = null
					const {
						cgp_id,
						leader_id,
					} = this.pageQueryPayload

					params = {
						cgp_id,
						leader_id,
					}

					apiCouponCGPGoods({
						...params
					}).then(data => {
						data.can_use.forEach(item => item.checked = false)
						return data
					}).then(data => {
						this.couponsInfo = this.$zhTran(data)
						// Tab名称处理（优惠券数量）
						this.couponTabsList.forEach(item => {
							switch (item.sign) {
								case 'usable':
									item.name = item.name + `(${ data.can_use_count })`
									break
								case 'disabled':
									item.name = item.name + `(${ data.not_can_use_count })`
									break
							}
						})
						this.couponTabsList = this.$zhTran(this.couponTabsList)
						resolve(data)
					}).catch(errMsg => reject(errMsg))
				})
			},

			// 更改优惠券
			changeCouponUse(coupon, value) {
				this.couponsInfo.can_use.forEach(item => item.checked = false)
				coupon && (coupon.checked = true)
			},

			// 使用优惠券
			useCoupon() {
				this.showCoupons = false
				const coupon = this.couponsInfo.can_use.find(item => item.checked)
				this.couponsActive = coupon || {}
				this.$set(this.orderFrom, 'coupon_list_id', coupon?.id)
				this.initOrderData()
			},

			// 打开优惠券弹窗
			openCouponsPopup() {
				if (Object.keys(this.couponsActive).length) {
					const coupon = this.couponsInfo.can_use.find(item => item.id === this.couponsActive.id)
					coupon.checked = true
				}
			},

			// 关闭优惠券弹窗
			closeCouponsPopup() {
				if (!Object.keys(this.couponsActive).length) {
					this.couponsInfo.can_use.forEach(item => item.checked = false)
				}
			},
			/** E 优惠券 **/
			async loadFunction() {
				// 初始化页面
				try {

					// 初始化页面数据
					await this.getLeaderInfo()
					await this.initOrderData()
					await this.initCouponGoods()

					this.pageStatus = PageStatusEnum['NORMAL']
				} catch (errMsg) {
					this.pageErrorMsg = errMsg
					this.pageStatus = PageStatusEnum['ERROR']
					console.log('页面数据初始化失败', errMsg)
				}
			},
			async onUnloadFunction() {
				setTimeout(() => {
					this.eventChannel2.emit("reCountCarNum", {});
				}, 500);
			}
		},

		async onLoad() {
			if (this.$Route.meta.atitle) {
				uni.setNavigationBarTitle({
					title: this.$zhTran(this.$Route.meta.atitle)
				})
			}
			const eventChannel2 = this.getOpenerEventChannel()
			this.eventChannel2 = eventChannel2
			eventChannel2.on("receiveData", (data) => {
				this.pageQueryPayload = data
				console.log('options', data)
				this.loadFunction();
			});
		},

		onUnload() {
			this.onUnloadFunction()
		}

	}
</script>

<style lang="scss" scoped>
	.leader-info {
		width: 100%;
		background-color: #fff;
		position: relative;
		border-radius: 10rpx;

		.info {
			width: calc(100% - 100rpx);
			color: rgba(166, 166, 166, 1);
			font-size: 24rpx;

			&>view {
				margin-bottom: 10rpx;
			}

			.address {
				color: rgba(56, 56, 56, 1);
				font-size: 28rpx;
			}

			.name {
				color: rgba(96, 98, 102, 1);
				font-size: 28rpx;

				.badge {
					background-repeat: no-repeat;
					background-size: 100% 100%;
					color: #fff;
					padding: 6rpx 15rpx;
					font-size: 22rpx;
				}
			}
		}
	}

	.leader-address {
		background-color: #fff;
		border-radius: 10rpx;

		.title {
			color: rgba(150, 150, 150, 1);
			font-size: 28rpx;
			margin-left: 20rpx;
		}

		text {
			color: rgba(56, 56, 56, 1);
		}
	}

	// Page style
	.goods-order {
		padding: 0 20rpx calc(100rpx + 20rpx + constant(safe-area-inset-bottom)) 20rpx;
		padding: 0 20rpx calc(100rpx + 20rpx + env(safe-area-inset-bottom)) 20rpx;

		// 卡片
		.contain {
			margin-top: 20rpx;
			border-radius: 7px;
			background-color: #FFFFFF;
			overflow: hidden;
		}

		// 单元格
		.cell {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: $-font-size-nr;
			color: $-color-black;

			&-label {
				width: 130rpx;
			}

			&-content {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: flex-end;
			}
		}

		// 初始化复选框的外边距
		.u-checkbox {
			::v-deep .u-checkbox__label {
				margin: 0;
			}
		}


		// 优惠
		.discounts {
			padding-left: 20rpx;

			&-item {
				height: 100rpx;
				padding-right: 20rpx;

				&:nth-child(n+2) {
					border-top: $-dashed-border;
				}
			}
		}
	}


	// 商品
	.goods {

		&-item {
			position: relative;

			&:nth-child(n+2)::before {
				position: absolute;
				left: 0;
				right: 0;
				top: 0;
				display: block;
				content: "";
				border-top: $-solid-border;
				margin-left: 20rpx;
			}

			&-widget {
				padding: 0 20rpx 0 calc((20rpx * 2) + 160rpx);

			}
		}

	}

	// 订单清算
	.clearing {
		padding: 20rpx;

		&-item {
			height: 70rpx;
		}
	}

	// 订单功能区
	.operational {
		box-sizing: border-box;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 100;
		height: calc(100rpx + constant(safe-area-inset-bottom));
		height: calc(100rpx + env(safe-area-inset-bottom));
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx constant(safe-area-inset-bottom) 20rpx;
		padding: 0 20rpx env(safe-area-inset-bottom) 20rpx;
		border-top: $-solid-border;
		background-color: #FFFFFF;

		.order-amount {
			font-size: &-font-size-nr;
			color: $-color-normal;
		}

		&-button {
			padding: 16rpx 45rpx;
			border-radius: 2px;
			font-size: 28rpx;
			color: rgba(74, 25, 0, 1);
			background-color: rgba(255, 209, 8, 1);
		}
	}

	// 优惠券【弹窗】
	.coupons {
		background-color: #f6f6f6;

		&-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 100rpx;
			padding: 0 30rpx;
			font-weight: 500;
			font-size: $-font-size-md;
			background-color: #FFFFFF;
		}

		&-main {
			&__tabs {
				border-top: $-solid-border;
			}

			&__contain {
				// margin-top: 20rpx;
				padding: 0 20rpx;
			}

			.coupons-item {
				margin-top: 20rpx;
			}
		}

		&-footer {
			display: flex;
			align-items: center;
			padding: 0 20rpx;
			height: 100rpx;
			background-color: #FFFFFF;

			&-button {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				height: 82rpx;
				border-radius: 60px;
				font-size: $-font-size-lg;
				@include background_color();
				color: #FFFFFF;
			}
		}
	}
</style>